package com.fom2008.receiver;

import java.util.regex.Pattern;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.gsm.SmsMessage;
import android.util.Log;

// Try to send an SMS with the following message:
//
// "geo:51.33,-0.74"
//
public class SMSReceiver extends BroadcastReceiver {

	// The Pattern to match against the message in order to ensure we have a
	// valid URI
	static final String	regExp	= "^geo:-?[0-9]+[\\.]*[0-9]*,-?[0-9]+[\\.]*[0-9]*$";

	static final String	ACTION	= "android.provider.Telephony.SMS_RECEIVED";

	@Override
	public void onReceive(Context context, Intent intent) {

		// Ensure the action is the one that we anticipate
		if (intent.getAction().equals(ACTION)) {

			// You can send parcels (equivalent to serializable) through
			// bundles. This is how we get the actual messages)
			Bundle bundle = intent.getExtras();
			if (bundle != null) {

				Object[] pdusObj = (Object[]) bundle.get("pdus");

				SmsMessage[] messages = new SmsMessage[pdusObj.length];

				for (int i = 0; i < pdusObj.length; i++) {
					messages[i] = SmsMessage.createFromPdu((byte[]) pdusObj[i]);

					if (Pattern.matches(regExp, messages[i].getMessageBody())) {
						// Start a new view against the location
						Intent mapIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(messages[i].getMessageBody()));
						// This is needed as we start from outside the activity
						// we are working on
						mapIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

						context.startActivity(mapIntent);
					}
				}
			}

		}
	}
}
